package cn.bestick.socket.demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by bestick on 2016/1/14.
 */
public class Server {

    public final int SERVER_PORT = 54321;

    public static void main(String[] args) {
        System.out.println("服务端启动...\n");
        new Server().init();
    }

    /**
     * server init method
     */
    public void init() {
        try {
            ServerSocket serverSocket = new ServerSocket(this.SERVER_PORT);
            while (true) {
                //一旦阻塞，证明客户端连接
                Socket client = serverSocket.accept();
                //处理这次连接
                new HandlerThread(client);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class HandlerThread implements Runnable {

        private Socket socket;

        public HandlerThread(Socket client) {
            this.socket = client;
            new Thread(this).start();
        }

        @Override
        public void run() {
            try {
                //读取客户端数据
                DataInputStream input = new DataInputStream(socket.getInputStream());
                String clientInputStr = input.readUTF();

                //处理客户端数据
                System.out.println("客户端发过来的数据是： " + clientInputStr);

                //向客户端回复信息
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                System.out.print("请输入： \t");

                //读取键盘输入数据
                String data = new BufferedReader(new InputStreamReader(System.in)).readLine();
                out.writeUTF(data);

                //关闭流
                out.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        socket = null;
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
